package employee;

import DBCP.MyDBCP;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@WebServlet("/employee")
public class EmployeeServlet extends HttpServlet {
    private static String getSalt(){
        char[] chars = new char[10];
        for (int i = 0; i < chars.length; i++) {
            chars[i] = (char)(Math.random()*(127-32)+32);
        }
        return new String(chars);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String action = req.getParameter("action");
            if (action.equals("signout")){
                signOut(req,resp);
            }
            if (action.equals("editer")){
                req.getSession().setAttribute("role",1);
                editer(req,resp);
            }
            if (action.equals("remove")){
                 remove(req,resp);
            }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           String action = req.getParameter("action");
           if (action.equals("signin")){
               signIn(req,resp);
           }
           if (action.equals("signup")){
               signUp(req,resp);
           }
           if (action.equals("addEmployee")){
              add(req,resp);
        }
           if (action.equals("update")){
            update(req,resp);
        }
    }
    //登录
    private void signIn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
           String username = req.getParameter("username");
           String password = req.getParameter("password");
           String selectSql = "select * from db_employee.employee where username = ? and password = md5(?)";
           String saltSql = "select * from db_employee.employee where username = ?";
           String updateSql = "update db_employee.employee set last_signin_time = ?,last_sigin_ip = ? where username = ?";
           Connection con = MyDBCP.getConnenction();
           PreparedStatement ps_sale = null;
           PreparedStatement ps_select = null;
           ResultSet rt = null;
           ResultSet resultSet = null;
        try {
            ps_sale = con.prepareStatement(saltSql);
            ps_sale.setString(1,username);
            rt = ps_sale.executeQuery();
            String SALT ="";
            int role = 0;
            if (rt.next()){
                SALT =rt.getNString("salt");
                role = rt.getInt("role");
            }
            try {
                ps_select = con.prepareStatement(selectSql);
                ps_select.setString(1,username);
                ps_select.setString(2,password+SALT);
                resultSet = ps_select.executeQuery();
                if (resultSet.next()){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    PreparedStatement ps_update = con.prepareStatement(updateSql);
                    ps_update.setString(1,sdf.format(new Date()));
                    ps_update.setString(2,req.getRemoteAddr());
                    ps_update.setString(3,username);
                    ps_update.executeUpdate();
                    req.getSession().setAttribute("username",username);
                    if (role == 0){
                        String employee_name = resultSet.getString("name");
                        String employee_email = resultSet.getString("email");
                        String employee_age = resultSet.getString("age");
                        String employee_gender = resultSet.getString("gender");
                        Employee employee = new Employee(employee_name,employee_email,employee_age,employee_gender);
                        req.getSession().setAttribute("employee",employee);
                        req.getSession().setAttribute("role",role);
                        resp.sendRedirect("Day03/employee/common/SystemHome.jsp");
                    }
                    if (role == 1){
                        selectAllEmployees(req,resp);
                        req.getSession().setAttribute("role",role);
                        resp.sendRedirect("Day03/employee/admin/Admin_Index.jsp");
                    }
                }else{
                    req.getSession().setAttribute("error","check your username and password!!");
                    resp.sendRedirect("Day03/employee/index.jsp");
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MyDBCP.close(rt,ps_sale,con);
            MyDBCP.close(resultSet,ps_select,con);
        }

    }
    //注册
    private void signUp(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
              addEmployee(req,resp,"Day03/employee/index.jsp","Day03/employee/SignUp.jsp");
    }
    //管理员编辑用户
    private void editer(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
            String editerId = "select name,email,age,gender from db_employee.employee where id = ?";
            int id = Integer.parseInt(req.getParameter("id"));
            Connection con = MyDBCP.getConnenction();
            PreparedStatement ps = null;
            ResultSet resultSet = null;
        try {
            ps = con.prepareStatement(editerId);
            ps.setInt(1,id);
            resultSet = ps.executeQuery();
            while (resultSet.next()){
                String name = resultSet.getString("name");
                String email = resultSet.getString("email");
                String age = resultSet.getString("age");
                String gender = resultSet.getString("gender");
                Employee employee = new Employee(id,name,email,age,gender);
                req.getSession().setAttribute("employee",employee);
                resp.sendRedirect("Day03/employee/admin/editer.jsp");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MyDBCP.close(resultSet,ps,con);
        }
    }
    //编辑之后更新用户
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
               String name = req.getParameter("name");
               String email = req.getParameter("email");
               String age =req.getParameter("age");
               String gender = req.getParameter("gender");
               int id = Integer.parseInt(req.getParameter("id"));
               String updateSql ="update db_employee.employee set name=?,email=?,age=?,gender=? where id = ?";
               Connection con =MyDBCP.getConnenction();
               PreparedStatement ps_update  = null;
        try {
            ps_update = con.prepareStatement(updateSql);
            ps_update.setString(1,name);
            ps_update.setString(2,email);
            ps_update.setString(3,age);
            ps_update.setString(4,gender);
            ps_update.setInt(5,id);
            ps_update.executeUpdate();
            selectAllEmployees(req,resp);
            resp.sendRedirect("Day03/employee/admin/Admin_Index.jsp");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MyDBCP.close(null,ps_update,con);
        }


    }
    //管理员删除用户
    private void remove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
           int id = Integer.parseInt(req.getParameter("id"));
           String delectSql = "delete  from  db_employee.employee where id = ?";
           Connection con = MyDBCP.getConnenction();
           PreparedStatement ps = null;
        try {
            ps  = con.prepareStatement(delectSql);
            ps.setInt(1,id);
            ps.executeUpdate();
            selectAllEmployees(req,resp);
            resp.sendRedirect("Day03/employee/admin/Admin_Index.jsp");
            ps.close();
            con.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MyDBCP.close(null,ps,con);
        }
    }
    //管理员添加用户
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
             addEmployee(req,resp,"Day03/employee/admin/Admin_Index.jsp","Day03/employee/admin/addemployee.jsp");
             selectAllEmployees(req,resp);
    }
    //添加用户
    private void addEmployee(HttpServletRequest req, HttpServletResponse resp,String successfulIndex,String errorIndex) throws ServletException, IOException {
          String username = req.getParameter("username");
          String password = req.getParameter("password");
          String name = req.getParameter("name");
          String email  = req.getParameter("email");
          String gender = req.getParameter("gender");
          String age = req.getParameter("age");
          String SALT = getSalt();
          String selectSql = "select username,email from db_employee.employee where username = ? or email = ?";
          String insertSql = "insert into db_employee.employee(username, password, salt, name, email, age, gender) values (?,md5(?),?,?,?,?,?)";

          Connection con = MyDBCP.getConnenction();
          PreparedStatement ps_select = null;
          PreparedStatement ps_insert = null;
          ResultSet resultSet = null;
        try {
            ps_select = con.prepareStatement(selectSql);
            ps_select.setString(1,username);
            ps_select.setString(2,email);
            resultSet = ps_select.executeQuery();
            if (resultSet.next()){
                String tempUserName = resultSet.getNString("username");
                String tempEmial = resultSet.getNString("email");
                if (username.equals(tempUserName) && email.equals(tempEmial)){
                    req.getSession().setAttribute("error","username and email is alreadly!");
                }else if (username.equals(tempUserName)){
                    req.getSession().setAttribute("error","username  is alreadly!");
                } else if (email.equals(tempEmial)) {
                    req.getSession().setAttribute("error","email is alreadly!");
                }

                resp.sendRedirect(errorIndex);
            }else {
                ps_insert = con.prepareStatement(insertSql);
                ps_insert.setString(1,username);
                ps_insert.setString(2,password+SALT);
                ps_insert.setString(3,SALT);
                ps_insert.setString(4,name);
                ps_insert.setString(5,email);
                ps_insert.setString(6,age);
                ps_insert.setString(7,gender);
                ps_insert.executeUpdate();
                req.getSession().setAttribute("message","Successful insert information!");
                resp.sendRedirect(successfulIndex);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MyDBCP.close(resultSet,ps_select,con);
            MyDBCP.close(null,ps_insert,con);
        }
    }
    //查询全体员工
    private void selectAllEmployees(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String selectAll = "select * from db_employee.employee where role = 0";
        Connection con = MyDBCP.getConnenction();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = con.prepareStatement(selectAll);
            rs = ps.executeQuery();
            ArrayList<Employee> employees = new ArrayList<Employee>();
            while (rs.next()){
                int employee_id = Integer.parseInt(rs.getString("id"));
                String employee_name = rs.getString("name");
                String employee_email =rs.getString("email");
                String employee_age = rs.getString("age");
                String employee_gender = rs.getString("gender");
                Employee emp = new Employee(employee_id,employee_name,employee_email,employee_age,employee_gender);
                employees.add(emp);
            }
            req.getSession().setAttribute("employees",employees);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MyDBCP.close(rs,ps,con);
        }
    }

    //登出
    private void signOut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         req.getSession().invalidate();
         resp.sendRedirect("Day03/employee/index.jsp");
    }
}
